import React, { Component, Fragment } from "react";
import { Button } from "antd";
import { Link } from "react-router-dom";
import $ from "jquery";
import { Upload, Icon, message, Tooltip } from "antd";
import "../assets/less/Human_body_search.less";
import Zmage from "react-zmage";
import { inject, observer } from "mobx-react";
import {
  base64_to_str,
  str_to_base64,
  img_format_size,
} from "../utils/utils";
@inject("AdminStore")
@inject("HumanBodyManageStore")
@observer
export default class Rentihome extends Component {
  constructor(props) {
    super(props);
    this.state = { base64_of_the_image_to_search_state: "", picture_file_state: "", uploading_state: false, body_retrieval_information_array: [], body_search_waits_for_image_to_load_icon_display_state: false, drawed: false };
  }
  Reset_human_body_search_all_state_data = () => {
    this.setState((prevState) => ({
      base64_of_the_image_to_search_state: "", picture_file_state: "", uploading_state: false, body_retrieval_information_array: []

    }))
  }
  componentDidMount() {
    window.scrollTo(0, 0);

  }
  clear_the_previously_drawn_diagram_fun(id) {
    var c = document.getElementById(id);
    c.height = c.height;
  }
  beforeUpload = async file => {
    if (this.state.drawed) {//清空canvas
      this.clear_the_previously_drawn_diagram_fun('canvasid')
    }
    await new Promise((resolve, reject) => {
      var fr = new FileReader();
      fr.onload = () => {
        const fileType = "image/pngimage/jpgimage/jpeg";
        if (fileType.indexOf(file.type) < 0) {
          message.info("请上传正确的图片格式");
          return false;
        } else if (file.size > 5 * 1024 * 1024) {
          message.info("图片不能大于5MB");
          return false;
        } else {
          let picture_base64 = fr.result; // picture_base64 没有格式转化的
          this.setState(prevState => ({
            base64_of_the_image_to_search_state: picture_base64,
            picture_file_state: file,
            body_search_waits_for_image_to_load_icon_display_state: true
          }));
          resolve(picture_base64);
        }
      };
      fr.readAsDataURL(file);
    });
    const human_feature_extraction_results = await this.props.HumanBodyManageStore.HumanFeatureExtractionFun(
      file,
      this.props.AdminStore.userName,
      this.props.AdminStore.token
    );
    console.log(human_feature_extraction_results)
    const upload_the_width_and_height_of_the_picture = await this.getUploadImageWidthAndHeight(this.state.base64_of_the_image_to_search_state)
    const div_current_width_and_height = this.getDivWidthAndHeight('alternate_image_id')
    let scaling = div_current_width_and_height[0] / upload_the_width_and_height_of_the_picture[0]
    var c = document.getElementById("canvasid");
    var ctx = c.getContext("2d");
    var img = document.getElementById("alternate_image_id");
    ctx.drawImage(img, (230 - div_current_width_and_height[0]) / 2, (350 - div_current_width_and_height[1]) / 2, div_current_width_and_height[0], div_current_width_and_height[1]);
    console.log('我在画图')
    ctx.strokeStyle = '#00B9EF'
    ctx.rect(human_feature_extraction_results.body_position.l * scaling + (230 - div_current_width_and_height[0]) / 2, human_feature_extraction_results.body_position.t * scaling + (350 - div_current_width_and_height[1]) / 2, human_feature_extraction_results.body_position.w * scaling, human_feature_extraction_results.body_position.h * scaling)
    ctx.stroke();
    this.setState((prevState) => ({
      body_search_waits_for_image_to_load_icon_display_state: false,
      drawed: true
    }))
  };
  picture_lazy_load() {
    $(function () {
      lazy_load();
      // 当页面开始滚动的时候，遍历图片，如果图片出现在视窗中，就加载图片
      var clock; //函数防抖
      $('.human_body_management_ul').on('scroll', function () {
        if (clock) {
          clearTimeout(clock);
        }
        clock = setTimeout(function () {
          lazy_load()
        }, 200)
      });
      function lazy_load() {
        $('.human_body_management_ul .ren_ti_jian_suo_right_ul_li_img').not('[data-isLoading]').each(function () {
          if (isShow($(this))) {
            loadImg($(this));
          }
        })
      }
      // 判断图片是否出现在视窗的函数
      function isShow($node) {
        if ($node.offset().top - 218 <= $('.human_body_management_ul').height()) {
          return true
        } else {
          return false
        }
      }
      // 加载图片的函数，就是把自定义属性data-src 存储的真正的图片地址，赋值给src
      function loadImg($img) {
        $img.css({ 'background-image': `url(${$img.attr('data-src')})` })
        // 已经加载的图片，我给它设置一个属性，值为1，作为标识
        // 弄这个的初衷是因为，每次滚动的时候，所有的图片都会遍历一遍，这样有点浪费，所以做个标识，滚动的时候只遍历哪些还没有加载的图片
        $img.attr('data-isLoading', 1);
      }
      // 一开始没有滚动的时候，出现在视窗中的图片也会加载
    })
  }
  getDivWidthAndHeight = id => {//返回数值
    let img = document.getElementById(id);
    let result = [];
    result.push(window.getComputedStyle(img).width);
    result.push(window.getComputedStyle(img).height);
    result[0] = result[0].split("px")[0];
    result[1] = result[1].split("px")[0];
    return result;
  };

  getUploadImageWidthAndHeight = url => {
    //这里返回的是一个promise
    var result = [];
    var p = new Promise(function (resolve, reject) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        result[0] = img.width;
        result[1] = img.height;
        resolve(result);
      };
    });
    return p;
  };

  human_feature_library_search_elements = async () => {//开始搜索函数
    this.setState(prevState => ({
      uploading_state: true
    }));
    //1.上传的图片中是否有人
    const catch_people = await this.props.HumanBodyManageStore.HumanFeatureExtractionFun(
      this.state.picture_file_state,
      this.props.AdminStore.userName,
      this.props.AdminStore.token
    );
    console.log(catch_people)
    //2.HumanFeatureExtractionFun
    if (catch_people.condition === 'success') {
      console.log(catch_people.body_position)

      const list_all_elements_of_the_feature_library = await this.props.HumanBodyManageStore.ListsAllElementsOfTheFeatureLibrary(this.props.AdminStore.userName, this.props.AdminStore.token)
      console.log(list_all_elements_of_the_feature_library)
      const human_feature_library_search_element_results = await this.props.HumanBodyManageStore.human_feature_library_search_elements(
        catch_people.feature_vector,
        this.props.AdminStore.userName,
        this.props.AdminStore.token
      );
      console.log(human_feature_library_search_element_results)

      let body_retrieval_information_array = []//人体信息搜索数组

      for (let [index, item] of list_all_elements_of_the_feature_library.entries()) {
        for (let [index1, item1] of human_feature_library_search_element_results.information_array.entries()) {
          if (item.user === item1['fnd-id'] || item.user.split('-')[1] === item1['fnd-id']) {
            body_retrieval_information_array.push(item)
            item.searchScore = item1.score
            if (item.user === item1['fnd-id']) {
              item.user = base64_to_str(item.user)
            }
          }
        }
      }
      function compare(key) {//属性搜索比较
        return function (value1, value2) {
          var val1 = value1[key];
          var val2 = value2[key];
          return val2 - val1;
        }
      }
      body_retrieval_information_array.sort(compare('searchScore'));
      this.setState((prevState) => ({
        body_retrieval_information_array: body_retrieval_information_array
      }), () => {
        this.picture_lazy_load()
      })
      if (human_feature_library_search_element_results.result === 'no_people_found') {
        $(function () {
          $('.human_body_management_ul').append(' <div class="no_data_class"><div class="no_data_word">暂无数据</div></div>')
        })
      }
    } else {
      this.Reset_human_body_search_all_state_data()
      message.info('未抓取到人体，请更换图片')
    }
  };
  render() {
    return (
      <Fragment>
        <div className="ren_ti_jian_suo_wrapper">
          <div className="ren_ti_jian_suo_left">
            <div className="ren_ti_jian_suo_left_content_wrap">
              <div className="ren_ti_jian_suo_left_content_wrap_top_decoration">
                <div className="ren_ti_jian_suo_left_content_wrap_top_decoration_describe">
                  上传图片
                </div>
              </div>
              <div className="ren_ti_jian_suo_left_content_wrap_top_line"></div>
              <div className="ren_ti_jian_suo_left_content_wrap_top_container">
                <Upload.Dragger beforeUpload={this.beforeUpload}>
                  {this.state.base64_of_the_image_to_search_state ? (
                    <React.Fragment>
                      <Icon type="loading" style={{ display: this.state.body_search_waits_for_image_to_load_icon_display_state ? 'block' : 'none' }} className="human_body_retrieval_waiting_for_image_loading_icon_class_name" />
                      <canvas id="canvasid" width="230px"
                        height="350px" className="ren_ti_jian_suo_left_content_wrap_top_container_img">
                      </canvas>
                      <img src={this.state.base64_of_the_image_to_search_state} id="alternate_image_id" alt="" />
                    </React.Fragment>
                  ) : (
                      <React.Fragment>
                        <div className="ren_ti_jian_suo_left_content_wrap_top_container_plus"></div>
                        <div className="ren_ti_jian_suo_left_content_wrap_top_container_describe">
                          选择图片
                      </div>
                      </React.Fragment>
                    )}
                </Upload.Dragger>
              </div>
              <Button
                className="ren_ti_jian_suo_left_content_wrap_top_button search_button_class"
                id="search_btn_1"
                onMouseEnter={() => {
                  $("#search_btn_1").css("background", "#007CDC");
                }}
                onMouseLeave={() => {
                  $("#search_btn_1").css("background", "#00A3FF");
                }}
                onClick={async () => {
                  this.setState((prevState) => ({
                    body_retrieval_information_array: []//重置数据
                  }))
                  await this.human_feature_library_search_elements()
                  this.setState(prevState => ({
                    uploading_state: false
                  }));
                }}
                loading={this.state.uploading_state}
              >
                {this.state.uploading_state ? "搜索中" : "搜索"}
              </Button>
            </div>
            <div className="attention">注：请上传全身人体图片</div>
          </div>
          <div className="ren_ti_jian_suo_right">
            <div className="human_body_management_ul human_search_ul_height">
              {this.state.body_retrieval_information_array.map((item, index) => {
                return (
                  <li key={index}>
                    <div className="similarity_class_name">{item.searchScore}%</div>
                    <div className="ren_ti_jian_suo_right_ul_li_img_wrap">
                      <a
                        onClick={() =>
                          Zmage.browsing({//修改这行代码记得下面还有一行和这个一模一样的
                            src: "/body/v1/image/store/" + item.src
                          })
                        }
                      >
                        <div
                          onClick={() => {
                            let that = this
                            $(function () {
                              $("#zmageImage").replaceWith(`<div class="imageLayer__33OvN" id="zmageImage" 
                                  style="background:url('/body/v1/image/store/${item.src}');visibility: visible"
                                ></div>`);
                              $('#zmageBackground').append('<div class="delete_icon_class"></div>')
                            })
                          }}
                          style={{
                            // backgroundImage: `url(/body/v1/image/store/` + item.src,
                            backgroundImage: "url(" + require('../assets/img/人体检索/暂无数据.png') + ")"
                          }}
                          data-src={`/body/v1/image/store/` + item.src}
                          className="ren_ti_jian_suo_right_ul_li_img"
                        ></div>
                      </a>
                    </div>

                    <div className="ren_ti_jian_suo_right_ul_li_people_icon_name_wrap">
                      <div className="ren_ti_jian_suo_right_ul_li_people_icon"></div>
                      <div className="ren_ti_jian_suo_right_ul_li_people_name">
                        <Tooltip title={(item.user)}>
                          <span>
                            {(item.user).length > 7
                              ? (item.user).substring(
                                0,
                                7
                              ) + "..."
                              : (item.user)}
                          </span>
                        </Tooltip>
                      </div>
                    </div>
                  </li>
                );
              })}
            </div>
          </div>
        </div>
      </Fragment>
    );
  }
}
